define(function (require, exports, module) {
    return function (jQuery) {
        (function ($) {

            //获取两个时间差时，返回月、天、小时、分钟
            var getTimeDiffValue = function(time1,time2,fmt){
                var minute = 1000 * 60;
                var hour = minute * 60;
                var day = hour * 24;
                var month = day * 30;

                var diffValue = 0;
                switch(fmt){
                    case 'month':
                        diffValue=(time1-time2)/month;
                        break;
                    case 'day':
                        diffValue=(time1-time2)/day;
                        break;
                    case 'hour':
                        diffValue=(time1-time2)/hour;
                        break;
                    case 'minute':
                        diffValue=(time1-time2)/minute;
                        break;
                    default:
                        break;
                }
                return diffValue;
            };

            /*seajs-content-start*/
            var customquectrl = function ($scope, httpservice) {
                var getTimeDiffValue = function(time1,time2,fmt){
                    var minute = 1000 * 60;
                    var hour = minute * 60;
                    var day = hour * 24;
                    var month = day * 30;

                    var diffValue = 0;
                    switch(fmt){
                        case 'month':
                            diffValue=(time1-time2)/month;
                            break;
                        case 'day':
                            diffValue=(time1-time2)/day;
                            break;
                        case 'hour':
                            diffValue=(time1-time2)/hour;
                            break;
                        case 'minute':
                            diffValue=(time1-time2)/minute;
                            break;
                        default:
                            break;
                    }
                    return diffValue;
                };
                var isTaskNameRepeat = false;
                var dateFormat = function (date, fmt) { //author: meizz
                    var o = {
                        "M+": date.getMonth() + 1,                 //月份
                        "d+": date.getDate(),                    //日
                        "h+": date.getHours(),                   //小时
                        "m+": date.getMinutes(),                 //分
                        "s+": date.getSeconds(),                 //秒
                        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                        "S": date.getMilliseconds()             //毫秒
                    };
                    if (/(y+)/.test(fmt))
                        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                        if (new RegExp("(" + k + ")").test(fmt))
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                };
                $scope.customtab = function(){
                    var startTime = new Date($("#starttime1").val());
                    var endTime = new Date($("#endtime1").val());
                    if(getTimeDiffValue(endTime,startTime,'day')>30){
                        alert('时间范围不能超过30天!');
                        return false;
                    }
                    if(new Date($("#endtime1").val())<new Date($("#starttime1").val())){
                        alert('开始时间不能大于结束时间!');
                        return false;
                    }
                    if(getTimeDiffValue(endTime,startTime,'day')>=7){
                        alert('时间范围不能超过7天!');
                        return false;
                    }
                    if($("#taskName").val() != ''){
                        if(!isTaskNameRepeat){
                            if($("#starttime1").val() != ''){
                                if($("#endtime1").val() != ''){
                                    if($("#starttime1").val()>$("#endtime1").val()){
                                        alert("起始时间不能大于结束时间！");
                                        return false;
                                    }
                                    if(($("#service_type").val() != '') ||($("#brand").val() != '') || ($("#keywordSource").val() != '')){

                                        if(($("#flowInterval").val() =='between' && $("#txtMinFlow").val() ==''&& $("#txtMaxFlow").val() !='' )||($("#flowInterval").val() =='between' && $("#txtMinFlow").val() !=''&& $("#txtMaxFlow").val() =='' )){
                                            alert("请填写完整的流量区间！");
                                            return false;
                                        }else{
                                            customQuery();

                                            $('.custompage1').hide();
                                            $('.custompage2').show();
                                            $('.selectfrom div:eq(0)').removeClass('customtab1').addClass('customtab2');
                                            $('.selectfrom div:eq(1)').removeClass('customtab2').addClass('customtab1');
                                        }
                                    }else{
                                        alert("请至少选择一种查询方案：业务选择、终端选择、关键字查询");
                                        return false;
                                    }
                                }else{
                                    alert("结束时间不能为空！");
                                    return false;
                                }
                            }else{
                                alert("开始时间不能为空！");
                                return false;
                            }
                        }else{
                            alert("任务名称重复，请重新设置！");
                            return false;
                        }
                    }else{
                        alert("任务名称不能为空！");
                        return false;
                    }
                };
                $scope.customtab1 = function(){
                    $("#taskName").val("");
                    $('.custompage1').show();
                    $('.custompage2').hide();
                    $('.selectfrom div:eq(0)').removeClass('customtab2').addClass('customtab1');
                    $('.selectfrom div:eq(1)').removeClass('customtab1').addClass('customtab2');
                };
                $scope.shi = function(){
                    $('.ts').show();
                };
                $scope.fou = function(){
                    $('.ts').hide();
                };
                $scope.ztreebus = {
                    obj: "",
                    filter: "",
//                    tofilter: function () { },
                    data: [
                        { id: 1, name: '全部', children: [
                            { id: 11, name: '游戏1' },
                            { id: 12, name: '游戏2' },
                            { id: 13, name: '游戏3' }
                        ]
                        }
                    ]
                };
                $scope.ztreeter = {
                    obj: "",
                    filter: "",
//                    tofilter: function () { },
                    data: [
                        { id: 1, name: '全部', children: [
                            { id: 11, name: 'P6' },
                            { id: 12, name: 'P7' },
                            { id: 13, name: 'p8' }
                        ]
                        }
                    ]
                };
                //检查任务名称是否重复
                $("#taskName").live("input",function(){
                    var conditon = {
                        taskName: $("#taskName").val()
                    }
                    var testName = httpservice.javaPost("customQuery.do?method=testName",conditon, function (result) {
                        if(result == 0){
                            isTaskNameRepeat = false;
                            $("#tip_name").html("");
                        }else{
                            isTaskNameRepeat = true;
                            $("#tip_name").html("<font color = 'red'> 任务名已存在！</font>");
                        }
                    });
                });

                //添加关键字
                $scope.addkeyword = function(){
                    var i=$('.dis input').size();
                    if(i>=5){
                        alert("关键字不能超过5个!");
                        return false;
                    }
                    $(".dis").append("<input /><img class='dingwei2' src='../../../images/delete1.png'>");
                };

                $(".dingwei2").live("click",function(){
                    $(this).prev().remove();
                    $(this).remove();
                });

                //选择流量区间
                $("#flowInterval").live("change",function(){
                    if($("#flowInterval").val() == 'between'){
                        $("#txtMinFlow").show();
                        $("#hide2").show();
                    }else{
                        $("#txtMinFlow").hide();
                        $("#hide2").hide();
                    }
                });
                //快速查询
                quickQuery = function(e){
                    $("#starttime1").val(dateFormat(new Date(new Date().setDate(new Date().getDate()-e)), "yyyy-MM-dd"));
                    $("#endtime1").val(dateFormat(new Date(new Date().setDate(new Date().getDate()-1)), "yyyy-MM-dd"));
                }
                //到任务管理界面
                toModel = function(){
                    window.location.href = "http://"+window.location.hostname+":"+window.location.port+"/default.html#/Model";
                }
                $scope.toModel = function (){
                    window.location.href = "http://"+window.location.hostname+":"+window.location.port+"/default.html#/Model";
                }
                //退出
                $scope.toHome = function(){
                    window.location.href ="http://"+window.location.hostname+":"+window.location.port+"/default.html#";
                }

                /*初始化业务*/
                var init_service = function(){
                    httpservice.javaPost("customQuery.do?method=serviceQuery",null, function (result) {
                        if(result.length>0){
                            var service_list = $("#service_type");
                            service_list.empty();
                            service_list.append("<option value=''></option>")
                            for(i=0;i<result.length;i++){
                                service_list.append("<option value='"+result[i]+"'>"+result[i]+"</option>")
                            }
                            $scope.$apply();
                        }
                    });
                }
                init_service();
                /*根据service查询sub_service*/
                var init_sub_ser = function(){
                    var condition={
                        service_type:$("#service_type").val()
                    };
                    var is=httpservice.javaPost("customQuery.do?method=service_typeQuery",condition, function (result) {
                        $scope.ztreebus.data = result;
                        $scope.$apply();
                    });
                }
                init_sub_ser();

                //根据选择的业务搜索子业务
                $("#service_type").live("change",function(){
                    init_sub_ser();
                });

                /*初始化终端品牌*/
                var init_terminal = function(){
                    httpservice.javaPost("customQuery.do?method=terminalQuery",null, function (result) {
                        if(result.length>0){
                            var brand_list = $("#brand");
                            //brand_list.empty();
                            //brand_list.append("<option value=''></option>")
                            for(i=0;i<result.length;i++){
                                brand_list.append("<option value='"+result[i]+"'>"+result[i]+"</option>")
                            }
                            $scope.$apply();
                        }
                    });
                }
                init_terminal();
                /*根据终端品牌查询终端型号*/
                var init_ter_type = function(){
                    var condition={
                        brand:$("#brand").val()
                    };
                    var is=httpservice.javaPost("customQuery.do?method=brandQuery",condition, function (result) {
                        $scope.ztreeter.data = result;
                        $scope.$apply();
                    });
                }
                init_ter_type();
                //根据终端品牌搜索终端型号
                $("#brand").live("change",function(){
                   init_ter_type();
                });

                //自定义查询任务的创建
                var customQuery = function(){
                    //任务名称
                    var taskName = $('#taskName').val();

    /*-------- ------------------------获得查询条件------------------------*/
                    var starttime =$('#starttime1').val();//起始日期
                    var endtime = $('#endtime1').val();//结束日期
                    //var userGroup =$('#userGroup').val();//用户组
                    var isExclude = 'false';   //是否排除用户
                    if($('#isExclude').attr("checked")=="checked"){
                        isExclude ='true';
                    }



                    var service_type = $('#service_type').val();//业务

                    var sub_service_type = "";//子业务
                    var s_type = "";//子业务名称
                    var serTree = $.fn.zTree.getZTreeObj("ztreebus");
                    var serNodes = serTree.getCheckedNodes(true);
                    for(i = 1; i < serNodes.length; i++) {
                        sub_service_type += serNodes[i].id+",";
                        s_type += serNodes[i].name+",";
                    }
                    sub_service_type = sub_service_type.substring(0,sub_service_type.length-1);
                    s_type = s_type.substring(0,s_type.length-1);


                    var brand = $('#brand').val();//终端品牌

                    var type = "";//终端型号
                    var terTree = $.fn.zTree.getZTreeObj("ztreeter");
                    var terNodes = terTree.getCheckedNodes(true);
                    for(i = 1; i < terNodes.length; i++) {
                        type += terNodes[i].name+",";
                    }
                    type = type.substring(0,type.length-1);


                    var keywordSource = $("#keywordSource").val();//关键字来源
                    var keyword = "";//关键字
                    $('.dis input').each(function(){
                        keyword += $(this).val()+",";
                    });
                    if(keyword !=""){
                        keyword = keyword.substring(0,keyword.length-1);
                    }


                    var flow = $("#flow").val();//流量
                    var flowInterval = $("#flowInterval").val(); //流量区间
                    var txtMinFlow = $("#txtMinFlow").val();
                    var txtMaxFlow = $("#txtMaxFlow").val();



                    var network_type="";//网络类型
                    $("input[name='network_type']:checkbox").each(function(){
                        if($(this).attr("checked")){
                            network_type += $(this).val()+","
                        }
                    });
                    network_type = network_type.substring(0,network_type.length-1);
    /*-------- ------------------------获得输出字段------------------------*/
                    var outputField = "";
                    var str="";
                    $("input[name='output']:checkbox").each(function(){
                        if($(this).attr("checked")){
                            str += $(this).val()+","
                        }
                    });
                    outputField = str.substring(0,str.length-1);


                    $('#taskN').html(taskName);
                    $('#createtime').html(dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss'));
                    $('#date').html(starttime+"~"+endtime);
                    $("#keyword").html("【"+keywordSource+"】"+" "+keyword);
                    $("#service").html("【"+service_type+"】"+" "+s_type);
                    $("#terminal").html("【"+brand+"】"+" "+type);
                    if(flowInterval == 'between'){
                        $("#other").html("【"+flow+"】"+" "+txtMinFlow+"k~"+txtMaxFlow+"k");
                    }else if(flowInterval == 'less'){
                        $("#other").html("【"+flow+"】"+" 小于"+txtMaxFlow+"k");
                    }else{
                        $("#other").html("【"+flow+"】"+" 大于"+txtMaxFlow+"k");
                    }
                    $("#output").html(" "+outputField);

    /*-------- ------------------------执行任务------------------------*/
                    /*var condition = {
                        taskName:taskName,
                        starttime:starttime,
                        endtime:endtime,
                        userGroup:userGroup,
                        isExclude:isExclude,
                        service_type:service_type,
                        sub_service_type:sub_service_type,
                        brand:brand,
                        type:type,
                        keywordSource:keywordSource,
                        keyword:keyword,
                        flow:flow,
                        flowInterval:flowInterval,
                        txtMinFlow:txtMinFlow,
                        txtMaxFlow:txtMaxFlow,
                        network_type:network_type,
                        outputField:outputField

                    };*/
                    var formData = new FormData();
                    formData.append("taskName",taskName);
                    formData.append("starttime",starttime);
                    formData.append("endtime",endtime);
                    //formData.append("userGroup",userGroup);
                    formData.append("isExclude",isExclude);
                    formData.append("service_type",service_type);
                    formData.append("sub_service_type",sub_service_type);
                    formData.append("brand",brand);
                    formData.append("type",type);
                    formData.append("keywordSource",keywordSource);
                    formData.append("keyword",keyword);
                    formData.append("flow",flow);
                    formData.append("flowInterval",flowInterval);
                    formData.append("txtMinFlow",txtMinFlow);
                    formData.append("txtMaxFlow",txtMaxFlow);
                    formData.append("network_type",network_type);
                    formData.append("outputField",outputField);
                    formData.append("file",$("#file")[0].files[0]);
                    $.ajax({
                        url:httpservice.javaserverurl+"customQuery.do?method=customQuery",
                        cache: false,
                        data: formData,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(result){
                            /*alert("新增成功");
                            getCommGroup();*/
                        },
                        error:function(result){
                            /*alert("新增失败");
                            getCommGroup();*/
                        }
                    });
                    /*var is=httpservice.javaPost("customQuery.do?method=customQuery",condition, function (result) {

                    });*/

                }


            };

            //setInterval();
            var modelctrl = function ($scope, httpservice) {
                var operate = function(cellvalue, options, rowObject){
                    var listprint = "<a class='viewmodel' href='javascript:'id='"+rowObject.id+"' title = '查看'><img src='../../../images/chakan.png' /></a>" +
                        "<a class='downloadmodel' style='margin: 0 15px;' href='javascript:'id='"+rowObject.id+"' state='"+rowObject.state+"' title='导出'><img src='../../../images/download.png' /></a>" +
                        "<a class='deletemodel' href='javascript:' id='"+rowObject.id+"' state='"+rowObject.state+"' title='删除'><img src='../../../images/delete1.png' /></a>";
                    return listprint;
                };
                $scope.modeldetail = {
                    title: "模型任务详情",
                    show: function () { },
                    ok: function () { },
                    cancel: function () { }
                };
                $(".viewmodel").live("click",function(){
                    var url="maketingModel.do?method=getmodelDetail";
                    var condition={
                        id:$(this).attr("id")
                    };
                    httpservice.javaPost(url,condition,function(result){
                        if(result.result==true){
                            $("#modeldetail").val(result.info);
                            $scope.modeldetail.show();
                        }else{
                            $scope.query();
                            alert("未获取到详细信息");
                        }
                    });


                });
                $(".downloadmodel").live("click",function(){
                    if($scope.isable($(this).attr("class"),$(this).attr("state"))){
                        var url="maketingModel.do?method=downloadfile&id="
                        window.location.href=httpservice.javaserverurl+url+$(this).attr("id");
                    }else{
                        alert("任务未完成或失败");
                    }
                });
                $(".deletemodel").live("click",function(){
                    var condition={
                        id:$(this).attr("id")
                    };

                    if($scope.isable($(this).attr("class"),$(this).attr("state"))){
                        if(confirm("确定删除任务吗？")){
                        var url="maketingModel.do?method=removeMaketModel"
                        httpservice.javaPost(url,condition,function(result){
                            $scope.getmodel($scope.getquerycondition());
                            alert(result.result);
                        });}
                    }else{
                        alert("不能删除该模型");
                    }
                });
                $scope.isable = function(classname,state){
                    if(classname=="downloadmodel"){
                        if(state=="成功"){
                            return true;
                        }else{
                            return false;
                        }
                    }else if(classname=="deletemodel"){
                        if(state=="成功"||state=="失败"){
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        return false;
                    }
                };

                $scope.init=function(){
                    $scope.query();
                    //setInterval("query()",5000);
                };
                $scope.getquerycondition = function(){
                    var condition = {
                        nowpage:$scope.grid1.gridpagedata.nowpage,
                        pagesize:$scope.grid1.gridpagedata.pagesize,
                        name:$("#modelName").val()
                    };
                    return condition;

                };
                $scope.query = function(){
                    $scope.getmodel($scope.getquerycondition());
                }
                $scope.getmodel = function(condition){
                    $scope.$emit('loading', 'true');
                    var url = "maketingModel.do";
                    var models=httpservice.javaPost(url,condition,function(result){
                        $scope.grid1.gridpagedata.totalcount = result.recordCount;
                        $scope.grid1.gridpagedata.totalpage = result.pageCount;
                        $scope.grid1.gridpagedata.startline =result.startLine;
                        $scope.grid1.gridpagedata.endline = result.endLine;
                        $scope.grid1.gridpagedata.datacount = result.dataCount;
                        $scope.grid1.griddata.data = result.datas;
                        $scope.$apply();
                    });
                    $.when(models).then(function () {
                    }).always(function () {
                        $scope.$emit('loading', 'false');
                        $scope.$apply();
                    });
                };
                $scope.grid1 = {
                    gridpagedata:{
                        nowpage:1,
                        totalpage:1,
                        totalcount:20,
                        startline:1,
                        endline:20,
                        pagesize:20,
                        datacount:20,
                        pagelist:[20,50,100],
                        toFirstpage: function(){
                            $scope.grid1.gridpagedata.nowpage = 1;
                            $scope.init();
                        },
                        toToppage: function(){
                            if($scope.grid1.gridpagedata.nowpage>1){
                                $scope.grid1.gridpagedata.nowpage--;
                            }
                            $scope.init();
                        },
                        toNextpage: function(){
                            if($scope.grid1.gridpagedata.nowpage<$scope.grid1.gridpagedata.totalpage){
                                $scope.grid1.gridpagedata.nowpage++;
                            }
                            $scope.init();
                        },
                        toLastpage: function(){
                            $scope.grid1.gridpagedata.nowpage = $scope.grid1.gridpagedata.totalpage;
                            $scope.init();
                        },
                        topage: function(){
                            if($scope.grid1.gridpagedata.nowpage<1){
                                $scope.grid1.gridpagedata.nowpage = 1;
                            }
                            if($scope.grid1.gridpagedata.nowpage>$scope.grid1.gridpagedata.totalpage){
                                $scope.grid1.gridpagedata.nowpage = $scope.grid1.gridpagedata.totalpage;
                            }
                            $scope.turnPage();
                        },
                        changePagesize: function(){
                            $scope.grid1.gridpagedata.nowpage = 1;
                            $scope.turnPage();
                        }
                    },
                    griddata: {
                        colnames: ['id','模型编号','模型名称',"模型属性",'模型状态','结果推送','操作人','操作时间',"操作"],
                        colmodel: [
                            { name: 'id', index: 'id', sortable: false, sorttype: 'number', align:"center",hidden:true},
                            { name: 'number', index: 'number', sortable: false, sorttype: 'number', align:"center"},
                            { name: 'name', index: 'name', sortable: false, align:"center"},
                            { name: 'property', index: 'property', sortable: false, align:"center"},
                            { name: 'state', index: 'state', sortable: true, align:"center"},
                            { name: 'propelresult', index: 'propelresult', sortable: true, align:"center"},
                            { name: 'opepeople', index: 'opepeople', sortable: true, align:"center"},
                            { name: 'cretime', index: 'cretime', sortable: true, align:"center"},
                            { name: 'operation', index: 'operation', sortable: false, align:"center",formatter:operate}
                        ],
                        data: [
//                            { number: "1",name: "和视频",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "2",name: "和阅读",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "3",name: "和视频",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "4",name: "和视频",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "5",name: "和视频",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "6",name: "和视频",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "7",name: "和阅读",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "8",name: "和阅读",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "9",name: "和阅读",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"},
//                            { number: "10",name: "和阅读",attribute: "业务营销", state: "已完成", push:"无", "operationuser":"张三", "operationtime": "2015-10-26 15:30"}
                        ]
                    },
                    obj:{},
                    shrinkToFit:true,
                    gridresize: function (grid) {
                        grid.setGridWidth($(window).width()-40);
                        grid.setGridHeight(400);
                    }
                };

               //$scope.init();
                setTimeout(function(){
                    $scope.init();
                },0);
                setInterval(function(){
                    $scope.init();
                },120000);




            };
            angular.module('customquery-ctrl', [])
                .controller('CustomqueCtrl', ['$scope', 'HttpService', customquectrl])
                .controller('ModelCtrl', ['$scope', 'HttpService', modelctrl]);
            /*seajs-content-end*/
        })(jQuery);
    }
});